/**
 * Copyright (c) 2011-2016, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.candy.db.generator.core;


import com.candy.db.generator.config.GlobalConfig;
import com.candy.db.generator.utils.BeanToMap;
import com.candy.db.generator.utils.FreeMarkerKit;
import com.candy.db.generator.utils.LogKit;
import com.candy.db.generator.utils.StrKit;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Base model 生成器
 */
public class ModelDaoGenerator {

	protected String modelPackageName;
	protected String modelDaoPackageName;
	protected String modelDaoOutputDir;

	protected JavaKeyword javaKeyword = new JavaKeyword();

	public ModelDaoGenerator(String modelDaoPackageName,String modelPackageName, String modelDaoOutputDir) {
		if (StrKit.isBlank(modelDaoPackageName))
			throw new IllegalArgumentException("modelDaoPackageName can not be blank.");
		if (modelPackageName.contains("/") || modelPackageName.contains("\\"))
			throw new IllegalArgumentException("modelDaoPackageName error : " + modelPackageName);
		if (StrKit.isBlank(modelDaoOutputDir))
			throw new IllegalArgumentException("modelDaoOutputDir can not be blank.");
		
		this.modelDaoPackageName = modelDaoPackageName;
		this.modelPackageName = modelPackageName;
		this.modelDaoOutputDir = modelDaoOutputDir;
	}
	
	public void generate(List<TableMeta> tableMetas) {
		System.out.println("Generate model dao ...");
		for (TableMeta tableMeta : tableMetas)
			genBaseModelContent(tableMeta);
	}
	
	protected void genBaseModelContent(TableMeta tableMeta) {
        String modelDaoName = tableMeta.modelName+"Dao";
        File file = new File(modelDaoOutputDir+File.separator+modelDaoName+ GlobalConfig.exportFileSuffix);
        if(file.exists() && !GlobalConfig.overrideForce){
            LogKit.debug("file :" + file.getAbsolutePath() + " exist! Ignore  it ...");
            return;
        }
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        Map rootMap = BeanToMap.Bean2Map(tableMeta);
        rootMap.put("modelDaoName",modelDaoName);
        rootMap.put("modelDaoPackageName",modelDaoPackageName);
        rootMap.put("modelPackageName",modelPackageName);
        rootMap.put("author",GlobalConfig.classAuthor);

        FreeMarkerKit.make(rootMap, "dao.ftl", file.getAbsolutePath());
	}
}






